package com.jl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.BASE64;
import com.jl.commons.utils.Md5Utils;
import com.jl.model.User;
import com.jl.model.in.UserGrade;
import com.jl.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用信息户表 前端控制器
 * </p>
 *
 * @author JiangJian
 * @since 2019-03-06
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @GetMapping("home")
    @RequiresPermissions("/user/home")
    public String homePage() {
        return "home";
    }


    @GetMapping("/userDataGrid")
    @RequiresPermissions("/user/userDataGrid")
    public String deviceList() {
        return "user_list";
    }


    @GetMapping("/add")
    @RequiresPermissions("/user/add")
    public String addUserPage(ModelMap mp, Long id) {
        mp.put("id", id);
        return "user_add";
    }

    @PostMapping("/add")
    @RequiresPermissions("/user/add")
    @ResponseBody
    public ResultData addUser(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        User user = JSON.parseObject(value, User.class);

        //新增数据
        user.setCreateId(getUserId());
        user.setGmtCreate(new Date());
        //判断登录名是否重复，不能拥有重复编号
        if (userService.isLoginNameUsed(user.getLoginName())) {
            //被占用
            return fail(ErrorCode.USER_LOGIN_NAME_USED, ErrorMessage.USER_LOGIN_NAME_USED);
        }
        userService.saveUser(user,user.getRoleId());
        return success(user);
    }


    @GetMapping("/edit")
    @RequiresPermissions("/user/edit")
    public String editUserPage(ModelMap mp, Long id) {
        mp.put("id", id);
        return "user_add";
    }

    @PostMapping("/edit")
    @RequiresPermissions("/user/edit")
    @ResponseBody
    public ResultData editUser(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        User user = JSON.parseObject(value, User.class);
        //更新数据
        user.setGmtModified(new Date());
        user.setModifyId(getUserId());
        if (Constants.DEFAULT_SHOW_PASSWORD.equals(user.getPassword())) {
            //表示密码没有被修改
            user.setPassword(null);
        } else {
            user.setPassword(Md5Utils.getMD5LowCase(user.getPassword()));
        }
        //判断登录名是不是自己的，如果是自己的则表示可以修改
        boolean canUse = userService.isLoginNameCanUse(user.getLoginName(), user.getId());
        if (!canUse) {
            return fail(ErrorCode.USER_LOGIN_NAME_USED, ErrorMessage.USER_LOGIN_NAME_USED);
        }
        userService.updateUserById(user,user.getRoleId());
        return success(user);
    }


    @PostMapping("/delete")
    @RequiresPermissions("/user/delete")
    @ResponseBody
    public ResultData deletesUser(String json) {
        String value = BASE64.decode(json);
        if (null == value) {
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value, Long.class);
        boolean b = userService.deleteUserByIds(ids);
        if (b) {
            return success();
        }
        return fail();
    }

    @PostMapping("/dataGrid")
    @RequiresPermissions("/user/dataGrid")
    @ResponseBody
    public ResultData userDataGrid(Long current, Long pageSize, String searchCol, String searchValue,String json) {
        if (current == null || pageSize == null) {
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //屏蔽系统用户
        queryWrapper.ne("t.id",0L);
        //目前的查询只有单表
        if(StringUtils.isNotBlank(json)){
            String value = BASE64.decode(json);
            JSONObject jsonObject = JSONObject.parseObject(value);
            if(StringUtils.isNotBlank(jsonObject.getString("username"))){
                queryWrapper.eq("t.username",jsonObject.getString("username"));
            }
            if(null!=jsonObject.getLong("organizationId") && jsonObject.getLong("organizationId")!=0){
                queryWrapper.eq("t.organization_id",jsonObject.getString("organizationId"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("description"))){
                queryWrapper.like("t.description",jsonObject.getString("description"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("phone"))){
                queryWrapper.eq("t.phone",jsonObject.getString("phone"));
            }
            if(null!=jsonObject.getLong("titleId") && jsonObject.getLong("titleId")!=0){
                queryWrapper.eq("t.title_id",jsonObject.getString("titleId"));
            }
            if(StringUtils.isNotBlank(jsonObject.getString("certificateTime"))){
                queryWrapper.like("t.certificate_time",jsonObject.getString("certificateTime"));
            }
        }else{
            if (StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)) {
                if (searchCol.equals(Constants.ID)) {
                    queryWrapper.eq("t.id", searchValue);
                } else {
                    queryWrapper.like("t." + searchCol, searchValue);
                }
            }
        }
        PageDataInfo<Map<String, Object>> pageDataInfo = new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        userService.selectUserDataGrid(pageDataInfo, queryWrapper);
        return success(pageDataInfo);
    }

    @GetMapping("/userInfo")
    @RequiresPermissions("/user/userGrade")
    public String userInfoPage(ModelMap modelMap,Long id){
        modelMap.put("id",id);
        return "userInfo";
    }

    @GetMapping("/modifyPassword")
    public String modifyPasswordPage(ModelMap modelMap,Long id){
        modelMap.put("id",id);
        return "modifyUserPassword";
    }

    @PostMapping("/modifyPassword")
    @ResponseBody
    public ResultData modifyPassword(Long id,String password){
        User user = new User();
        user.setId(id);
        user.setPassword(Md5Utils.getMD5LowCase(password));
        user.setGmtModified(new Date());
        user.setModifyId(getUserId());
        userService.updateById(user);
        return success(user);
    }


    @GetMapping("/userGrade")
    @RequiresPermissions("/user/userGrade")
    public String userGradePage(){
     return "userGrade_list";
    }

    @PostMapping("/userGrade")
    @RequiresPermissions("/user/userGrade")
    @ResponseBody
    public ResultData userGrade(Long userId,String month) {
        PageDataInfo<UserGrade> pageDataInfo = new PageDataInfo<>();
        pageDataInfo.setCurrent(Constants.FIRST_PAGE);
        pageDataInfo.setSize(Constants.MAX_PAGE_SIZE);
        userService.getAllUserGrade(pageDataInfo,month,userId);
        return success(pageDataInfo);
    }


}
